﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"
//打印函数
void print(SL* s) {
	for (int i = 0; i < s->size; i++) {
		printf("%d ", s->arr[i]);
	}
	printf("\n");
}
/*内存空间判断函数实现*/
void CheackCapaceity(SL* s) {
	if (s->capaceity == s->size) {
		int newcapaceity = s->capaceity == 0 ? 4 :2 * s->capaceity;//s->capaceity可能为0
		int* temp = (int*)realloc(s->arr, newcapaceity * sizeof(int));//内存可能申请失败，最好用中间变量先代替
		if (temp == NULL) {
			perror("realloc faill");
			exit(1);
		}
		s->arr = temp;
		s->capaceity = newcapaceity;
	}
}


//顺序表初始化函数实现
void InitSeqList(SL* s) {
	s->arr = NULL;
	s->capaceity = s->size = 0;
}
//顺序表尾插函数实现
void SLPushBack(SL* s, SLDateType x) {
    /*内存空间判断函数*/
	CheackCapaceity(s);
	s->arr[s->size++] = x;//尾插
}
//顺序表头插函数实现
void SLPushFront(SL* s, SLDateType x) {
	/*内存空间判断函数*/
	CheackCapaceity(s);
	for (int i = s->size; i > 0; i--) {
		s->arr[i] = s->arr[i-1];
	}
	/*s->arr[0] = x;*/
	s->size++;
	s->arr[0] = x;
}
//顺序表头删函数实现
void SLpopFront(SL* s) {
	assert(s);
	assert(s->size);
	for (int i = 0; i < s->size - 1; i++) {
		s->arr[i] = s->arr[i + 1];
	}
	s->size--;
}
//顺序表尾删函数实现
void SLpopBack(SL* s) {
	assert(s);
	assert(s->size);
	s->size--;
}
//指定位置之前插⼊
void SLInsert(SL* s, int pos, SLDateType x) {
	assert(s);
	assert(pos >= 0 && pos < s->size);
	/*内存空间判断函数*/
	CheackCapaceity(s);
	for (int i = s->size; i > pos; i--) {
		s->arr[i] = s->arr[i - 1];
	}
	s->arr[pos] = x;
	s->size++;
}
//指定位置删除
void SLErase(SL* s, int pos) {
	assert(s);
	assert(pos>=0&&pos<s->size);
	for (int i = pos; i < s->size; i++) {
		s->arr[i] = s->arr[i + 1];
	}
	s->size--;
}
//查找
int SLFind(SL* s, SLDateType x) {
	assert(s);
	for (int i = 0; i < s->size; i++){
		if (s->arr[i] == x) {
			return i;//找到
		}
	}
	return -1;//未找到
}
//顺序表销毁函数实现
void DestorySeqList(SL* s) {
	if (s->arr) //等价于  if(ps->arr != NULL)
	{
		free(s->arr);
	}
	s->arr = NULL;
	free(s->arr);
	s->capaceity = s->size = 0;
}